import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import QThread, pyqtSignal, QWaitCondition, QMutex
from PySide2.QtUiTools import QUiLoader
from PyQt5.QtWidgets import QApplication, QMessageBox, QTableWidgetItem, QFileDialog, QMainWindow
from GetHostIP import HostIP
import socket
from time import localtime
from appui3 import Ui_MainWindow


class Stats(QMainWindow):
    def __init__(self):
        super(Stats, self).__init__()
        self.ip = HostIP().ip
        self.port = 4433
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUi()

        self.HPortStatus = 0
        self.DIPStatus = 0
        self.DPortStatus = 0



        self.udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.threadRecv = RecvDataThread(self)
        self.threadRecv.sig.connect(self.recvData)

    def initUi(self):
        self.setWindowTitle("网络调试助手")
        self.ui.pushButton_2.setEnabled(False)  # 发送
        # self.ui.pushButton_3.setEnabled(False)  # 连接
        self.ui.pushButton_4.setEnabled(False)  # 保存
        self.ui.pushButton_3.clicked.connect(self.establishConnection)
        self.ui.pushButton_2.clicked.connect(self.sendData)
        self.ui.pushButton.clicked.connect(self.clearTextBrowser)
        self.ui.pushButton_5.clicked.connect(self.clearLineText)
        self.ui.pushButton_4.clicked.connect(self.saveLog)
        self.ui.comboBox_2.addItem(self.ip)
        self.ui.lineEdit_6.setText('4433')

    def clearTextBrowser(self):
        self.ui.textBrowser.clear()

    def clearLineText(self):
        self.ui.lineEdit_5.clear()

    def infoCompleted(self):
        self.isDestPort()
        self.isDestIP()
        if self.DPortStatus * self.DIPStatus == 1:
            return True
        return False

    def bindSocket(self):
        self.port = int(self.ui.lineEdit_6.text())
        self.ip = self.ui.comboBox_2.currentText()
        self.udpSocket.bind((self.ip, self.port))
        print( self.ip, self.port)

    def establishConnection(self):
        if self.infoCompleted():
            self.bindSocket()
            self.ui.pushButton_4.setEnabled(True)
            self.ui.textBrowser.append("OK")
            self.ui.pushButton_2.setEnabled(True)
            self.threadRecv.start()

    def saveLog(self):
        mainWindow = QMainWindow()
        msgBox = QMessageBox()
        filePath = QFileDialog.getSaveFileName(mainWindow, u'选择要保存的位置', './log.txt', '*')[0]
        log = str(self.ui.textBrowser.toPlainText())
        with open(filePath, "a") as f:
            f.write(log)
        QMessageBox.information(msgBox, '提示', '保存成功!')

    def isDestPort(self):
        dest_port = self.ui.lineEdit_3.text()
        if dest_port is not None and dest_port != '':
            self.DPortStatus = 1

    def isDestIP(self):
        dest_ip = self.ui.lineEdit_4.text()
        if dest_ip is not None and dest_ip != '':
            self.DIPStatus = 1

    def recvData(self, info):
        t = localtime()
        tStr = str(t.tm_hour) + ':' + str(t.tm_min) + ':' + str(t.tm_sec)
        info = eval(info)
        addr = str(info[0]).replace('(', '[').replace(')', ']')
        data = info[1]
        self.ui.textBrowser.append(addr + '\t' + tStr)
        self.ui.textBrowser.append('>>' + data + '\n')

    def sendData(self):
        print('---------------1----------------')
        data = self.ui.lineEdit_5.text()
        print('---------------2----------------')
        print(data)
        dest_ip = self.ui.lineEdit_4.text()
        print('---------------3----------------')
        print(dest_ip)
        dest_port = self.ui.lineEdit_3.text()
        print('---------------4----------------')
        print(dest_port)
        self.udpSocket.sendto(data.encode("gb2312"), (dest_ip, dest_port))
        print('---------------5----------------')

class RecvDataThread(QThread):
    sig = pyqtSignal(str)  # 自定义信号对象。参数str就代表这个信号可以传一个字符串
    def __init__(self, body):
        super(RecvDataThread, self).__init__()
        self.udpSocket = body.udpSocket
        self.ui = body.ui
        self.body = body

    def run(self):
        while True:
            rec_info = self.udpSocket.recvfrom(1024)
            addr = str(rec_info[1])
            data = rec_info[0].decode("gb2312")
            info = str([addr, data])
            self.sig.emit(info)


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    stats = Stats()
    stats.show()
    app.exec_()
